<template>
  <el-dialog v-model="visible" width="400px" @close="onClose">
    <template #header>
      <div class="my-header"> 导出 </div>
    </template>
    <el-form ref="formRef" :model="formParams" label-width="80px">
      <el-form-item
        label="导出数量"
        prop="count"
        :rules="[{ required: true, message: '', trigger: 'blur' }]"
      >
        <el-input-number
          @mousewheel.native.prevent
          v-model="formParams.count"
          :precision="0"
          :min="1"
          :max="maxNum > 10000 ? 10000 : maxNum"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleAction(false)">取消</el-button>
      <el-button :loading="submit" type="primary" @click="handleAction(true)"> 导出 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
const { proxy } = getCurrentInstance()

const emit = defineEmits(['refresh'])
const formRef = ref(null)
const visible = ref(false)
const submit = ref(false)
const formParams = reactive({
  count: undefined,
  marCouponId: ''
})

const maxNum = ref(1)
function handleAction(confirm) {
  if (confirm) {
    formRef.value.validate((valid) => {
      if (valid) {
        submit.value = true
        proxy
          .download(
            '/operation/marCoupon/derive',
            { ...formParams },
            `优惠券列表${new Date().getTime()}.zip`
          )
          .then(() => {
            onClose()
            emit('refresh')
          })
          .catch((err) => {
            submit.value = false
          })
      }
    })
  } else {
    onClose()
  }
}

function onClose() {
  formRef.value.resetFields()
  submit.value = false
  visible.value = false
}
const init = (row) => {
  maxNum.value = row.surplusCount
  formParams.marCouponId = row.id
  visible.value = true
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped></style>
